package com.hanhai.material.config.security;

import com.alibaba.fastjson.JSON;
import com.hanhai.material.common.result.ResultTool;
import lombok.extern.log4j.Log4j2;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author youchuang
 * @description:登录失败处理
 **/
@Component
@Log4j2
public class LoginFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request,
                                        HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException {
        //设置客户端响应编码格式
        response.setContentType("application/json;charset=UTF-8");
        //获取输出流
        ServletOutputStream outputStream = response.getOutputStream();
        String message = null;//提示信息
        int code = 500;//错误编码
        log.error(exception);
        //判断异常类型
        if (exception instanceof AccountExpiredException) {
            message = "用户名过期，登录失败！";
        } else if (exception instanceof BadCredentialsException) {
            message = "用户名或密码错误，登录失败！";
        } else if (exception instanceof CredentialsExpiredException) {
            message = "密码过期，登录失败！";
        } else if (exception instanceof DisabledException) {
            message = "用户被禁用，登录失败，请联系管理员！";
        } else if (exception instanceof LockedException) {
            message = "用户名被锁，登录失败！";
        } else if (exception instanceof InternalAuthenticationServiceException) {
            message = "用户名不存在，登录失败！";
        } else {
            message = "验证码错误！";
        }
        //将错误信息转换成JSON
        String result = JSON.toJSONString(ResultTool.fail(message));
        outputStream.write(result.getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
    }
}

